<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国项目/钻孔总体数据'" />
          <Amount :data="data" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'各省（直辖市）项目数据统计'" />
          <BarChart :listData="getItemData" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'各省（直辖市）钻孔数据统计'" />
          <LineCharts v-if="isShow" :listData="getDrillData" />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="'全国地震安全性评价和钻孔位置分布图'" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '0px', left: '42px' }" />
          <!-- <IndexMap></IndexMap> -->
          <OlMap :refId="'projectDrill'" style="height: 100%" @getMap="getMap"></OlMap>
          <!--<div class="legend">
            <img src="@/assets/map/image/newImage/point_project.png" style="scale: 0.9" />
            <span style="margin-right: 10px; font-size: 14px; color: #ffffff">项目</span>
            <img src="@/assets/map/image/newImage/point_drill.png" style="scale: 0.9" />
            <span style="font-size: 14px; color: #ffffff">钻孔</span>
          </div>-->
          <div class="drillGridCountRadioDiv">
            <el-radio-group v-model="drillGridCountRadio" @change="addDrillGridCountLayer" class="radio1">
              <el-radio :label="0">安评区评小区划钻孔数量</el-radio>
              <el-radio :label="1">勘察孔数量</el-radio>
            </el-radio-group>
          </div>
          <ComLegend
              style="position: absolute; left: 42px; bottom: 220px"
              title="图例"
              subTitle="钻孔数量"
              :items="legendItems"
              :items-per-column="10"
          ></ComLegend>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国项目/钻孔总体数据更新'" />
          <UpdateData
            v-if="isShow1"
            :projectDrillTotalUpdata="projectDrillTotalUpdata"
            :type="type"
            @onClick="onClick"
          />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国项目/钻孔年份数据更新'" />
          <Stacked :yearRenewal="yearRenewal" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'不同工程类别数据统计'" />
          <EngineeringData :list="workCategoryCount" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
import { getLonAndLat } from '@/api/projectDrill.js';
import OlMap from '@/components/Olmap';
import { DoubleClickZoom, MouseWheelZoom, DragPan } from 'ol/interaction';
import { Style, Circle as CircleStyle, Fill, Stroke, Text, Icon } from 'ol/style';
import { Feature } from 'ol';
import { Point } from 'ol/geom';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { getChinaBaseMap, getBaseDir,getGridLayer } from '@/map/projMap.js';

import point_drill_img from '@/assets/map/image/newImage/point_drill.png';
import point_project_img from '@/assets/map/image/newImage/point_project.png';

import {
  getProjectDrillNum,
  getProvinceCount,
  getProjectDrillRenew,
  getYearProjectDrillRenew,
  getWorkCategoryCount,
} from '@/api/drillApi.js';
import { getActivityMap } from '@/api/securityActivity.js';
import Amount from './components/Amount';
import BarChart from './components/BarChart';
import LineCharts from './components/linecharts';
import UpdateData from './components/UpdataData';
import Stacked from './components/Stacked';
import EngineeringData from './components/engineeringData';
import ComLegend from './components/ComLegend';
import {ref} from "vue";

// 地震个数统计
let totalNum = '1024';
const totalArr = ref([]);
const mapInstance = ref(null);
const vectorLayer = ref(null);
const overlayLayer = ref(null);
const customIconLayer = ref(null);
const selectInteraction = ref(null); // 选择交互对象
totalArr.value = Array.from(totalNum);
const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);

  addProvinceNameLayer();
  addCustomerLayer();
  // addLonAndLatData();
  // 假数据
  // addDrillIconLayer();
  // addProjectIconLayer();
  addDrillGridCountLayer();//钻孔计数公里格网图层
};
function addCustomerLayer() {
  customIconLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 3,
  });

  mapInstance.value.addLayer(customIconLayer.value);
}
function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 2,
    style: function (feature) {
      const textstyle = new Style({
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#fff' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}
const addLonAndLatData = () => {
  getLonAndLat().then((res) => {
    let projectData = res?.data[0];
    let drillData = res?.data[1];
    if (projectData && projectData.length > 0) {
      addLayer('project', projectData);
    }
    if (drillData && drillData.length > 0) {
      addLayer('drill', drillData);
    }
  });
};
const addLayer = (type, data) => {
  for (let i = 0; i < data.length; i++) {
    let item = data[i];
    const pointFeature = new Feature({
      geometry: new Point([item.lon, item.lat]),
    });
    pointFeature.setStyle(getStyle(type));
    customIconLayer.value.getSource().addFeature(pointFeature);
  }
};
const getStyle = (type) => {
  return new Style({
    image: new Icon({
      src: type == 'project' ? point_project_img : point_drill_img,
      anchor: [0.5, 0.5],
      scale: 0.8,
    }),
  });
};

function addProjectIconLayer() {
  const geojsonSource = new VectorSource({
    url: getBaseDir('projectPoint.json'),
    format: new GeoJSonFormat(),
  });

  const customIconStyle = new Style({
    image: new Icon({
      src: point_project_img,
      anchor: [0.5, 0.5],
      scale: 0.5,
    }),
  });

  const customIconLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 3,
    style: customIconStyle,
  });

  mapInstance.value.addLayer(customIconLayer);
}

function addDrillIconLayer() {
  const geojsonSource = new VectorSource({
    url: getBaseDir('drillPoint.json'),
    format: new GeoJSonFormat(),
  });

  const customIconStyle = new Style({
    image: new Icon({
      src: point_drill_img,
      anchor: [0.5, 0.5],
      scale: 0.5,
    }),
  });

  const customIconLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 3,
    style: customIconStyle,
  });

  mapInstance.value.addLayer(customIconLayer);
}

//是否显示图层
function setLayerVisible(layerId, flag) {
  let layers = mapInstance.value.getLayers();
  layers.forEach((layer) => {
    let lid = layer.get('id');
    if (lid) {
      if (lid.indexOf(layerId) != -1) {
        layer.setVisible(flag);
      }
    }
  });
}

//是否已有图层
function getLayerBool(layerId) {
  let bool = false;
  let layers = mapInstance.value.getLayers();
  layers.forEach((layer) => {
    let lid = layer.get('id');
    if (lid) {
      if (lid.indexOf(layerId) != -1) {
        bool = true;
      }
    }
  });
  return bool;
}

const legendItems = ref([
  { label: '0', color: 'rgba(0,0,0,0)', w: 10, h: 8, r: 0, borderColor: "gray" },
  { label: '1', color: '#deee05', w: 10, h: 8, r: 0, borderColor:"rgba(0,0,0,0)" },
  { label: '2-5', color: '#ff8f02', w: 10, h: 8, r: 0, borderColor:"rgba(0,0,0,0)" },
  { label: '6-9', color: '#d90100', w: 10, h: 8, r: 0, borderColor:"rgba(0,0,0,0)" },
  { label: '10 及以上', color: '#610100', w: 10, h: 8, r: 0, borderColor:"rgba(0,0,0,0)" },
]);

//0安评区评小区划钻孔数量 1勘察孔数量
const drillGridCountRadio = ref(0);
const drillGridCountLayer0 = ref(null);
const drillGridCountLayer1 = ref(null);
//钻孔计数公里格网图层
function addDrillGridCountLayer(){
  let type = drillGridCountRadio.value;
  let layerId = 'drillGridCount_'+type;
  let url = '/iserver/services/map-fxfzdzqh/rest/maps/dzqh_china_grid_kilometer_pf_other@fxfzdzqh';//0安评区评小区划钻孔数量
  if(type==1){
    url = '/iserver/services/map-fxfzdzqh/rest/maps/dzqh_china_grid_kilometer_pf@fxfzdzqh';//1勘察孔数量
    setLayerVisible("drillGridCount_0",false);
  }else{
    setLayerVisible("drillGridCount_1",false);
  }
  //是否已有图层
  if(getLayerBool(layerId)){
    setLayerVisible(layerId,true);
  }else{
    getGridLayer(url).then((layer) => {
      layer.set('id', layerId);
      layer.setZIndex(6);
      mapInstance.value.addLayer(layer);
    });
  }
}

const setupSelectInteraction = () => {
  // 监听地图的点击事件
  mapInstance.value.on('click', (event) => {
    const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
    if (features.length > 0) {
      const selectedFeature = features[0];
      // 在这里添加处理点击事件的逻辑
      console.log('点击了要素：', selectedFeature.getProperties());
    }
  });
};
const createOverlayLayer = () => {
  overlayLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 9999,
  });
  mapInstance.value.addLayer(overlayLayer.value);
};
const createVectorLayer = () => {
  vectorLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 2,
  });
  mapInstance.value.addLayer(vectorLayer.value);
};
const addRandomPoints = () => {
  if (!vectorLayer.value) {
    return;
  }
  const provinces = [
    { lonMin: 97.35, lonMax: 108.16, latMin: 26.0, latMax: 34.91 }, // 四川
    { lonMin: 78.0, lonMax: 99.12, latMin: 26.0, latMax: 36.3 }, // 西藏
    { lonMin: 105.66, lonMax: 110.19, latMin: 28.03, latMax: 32.13 }, // 重庆
  ];

  for (let i = 0; i < 100; i++) {
    const province = provinces[Math.floor(Math.random() * provinces.length)];
    const lon = Math.random() * (province.lonMax - province.lonMin) + province.lonMin;
    const lat = Math.random() * (province.latMax - province.latMin) + province.latMin;
    const color = getRandomColor();

    const point = new Feature({
      geometry: new Point([lon, lat]),
    });

    const style = new Style({
      image: new CircleStyle({
        radius: 8,
        fill: new Fill({ color }),
        stroke: null, // 取消边框
      }),
    });

    point.setStyle(style);
    vectorLayer.value.getSource().addFeature(point);
  }
};
const getRandomColor = () => {
  const randomColor = Math.floor(Math.random() * 16777215).toString(16);
  return `#${'0'.repeat(6 - randomColor.length)}${randomColor}`;
};

// 全国项目/钻孔总体数据
const data = ref({});
//各省（直辖市）项目数据统计
const getItemData = ref([]);
//各省（直辖市）钻孔数据统计
const getDrillData = ref([]);
// 全国项目/钻孔总体数据更新
const projectDrillTotalUpdata = ref([]);
const type = ref(0);
// 全国项目/钻孔年份数据更新
const yearRenewal = ref([]);
// 不同工程类别数据统计
const workCategoryCount = ref([]);
const isShow = ref(false);
const isShow1 = ref(false);
getDrillNum();
provinceCount(0);
provinceCount(1);
getDrillRenew(0);
getYearDrillRenew();
getCategoryCount();

const onClick = (val) => {
  type.value = val;
  getDrillRenew(val);
};
function getDrillNum() {
  getProjectDrillNum().then((res) => {
    data.value = res.data;
  });
}
function provinceCount(type) {
  getProvinceCount({ type }).then((res) => {
    isShow.value = true;
    if (type == '0') {
      getItemData.value = res.data;
    } else {
      getDrillData.value = res.data;
    }
  });
}
function getDrillRenew() {
  getProjectDrillRenew().then((res) => {
    isShow1.value = true;
    projectDrillTotalUpdata.value = res.data;
  });
}
function getYearDrillRenew() {
  getYearProjectDrillRenew().then((res) => {
    yearRenewal.value = res.data;
  });
}
function getCategoryCount() {
  getWorkCategoryCount().then((res) => {
    workCategoryCount.value = res.data;
  });
}
</script>

<style scoped lang="scss">
.app-main {
  display: flex;
  justify-content: space-between;

  .app-left {
    margin-left: 30px;
    // margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;
    &-item {
      width: 450px;
      height: 300px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      color: #fff;
      // position: absolute;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
      &:nth-child(2) {
        height: 300px;
        z-index: 10;
      }
      &:nth-child(3) {
        height: 300px;
      }
    }
  }

  .app-map {
    width: 960px;
    height: 100%;
    //overflow: hidden; //test
    position: relative;
    /*.legend {
      position: absolute;
      bottom: 20%;
      left: 42px;
      display: flex;
      flex-direction: row;
      align-items: center;
    }*/

    .drillGridCountRadioDiv {
      position:absolute;top:20px;right:20px;
    }
    .el-radio {
      margin: 4px 0;
      padding-left: 12px;
      color: #fff;
      font-size: 18px;
    }
    .radio1 {
      display: flex;
      width: 100%;
    }
  }
  .app-right {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;

    &-item {
      width: 450px;
      height: 300px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
    }
  }
}
</style>
